/*
 * @author zei , QQ:77132995, email:kazeik@163.com
 * 2022-03-12 14:12
 * 类说明:
 */
import 'package:base_plugin/base_plugin.dart';
import 'package:extended_nested_scroll_view/extended_nested_scroll_view.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/common/config.dart';
import 'package:finance_app/src/entities/setting_data_import_summary_list_entity.dart';
import 'package:finance_app/src/http_service/http_coa_service.dart';
import 'package:finance_app/src/widgets/bottom_sheet/date_time_select_bottom_sheet.dart';
import 'package:finance_app/src/widgets/bottom_sheet/delete_info_bottom_sheet.dart';
import 'package:finance_app/src/widgets/bottom_sheet/got_it_tip_bottom_sheet.dart';
import 'package:flutter/material.dart';
import 'package:quiver/strings.dart';

class SettingDataImportSummaryProvider extends BaseProvider<List<SettingDataImportSummaryListEntity>> {
  TextEditingController searchController = TextEditingController();
  FocusNode searchFocusNode = FocusNode();
  DateTime startDate;
  DateTime asAt = DateTime.parse(Config.currentFY.endDate);

  num totalDebit = 0.0;
  num totalCredit = 0.0;
  String difference = '';

  List<String> fileItems = [];

  SettingDataImportSummaryProvider(this.fileItems);

  @override
  Future get dataFuture => HttpCoaService.getInitCoa();

  void updateBalance(String value, int index) {
    if (index > data.length) return;
    data[index].default_balance = isEmpty(value) ? 0 : num.parse(value);
    _calculateDiffData();
    update();
  }

  @override
  FutureOr<List<SettingDataImportSummaryListEntity>> transformData(List<SettingDataImportSummaryListEntity> d, bool isCache) {
    _calculateDiffData();
    return super.transformData(d, isCache);
  }

  void _calculateDiffData() {
    num debit = 0.0;
    num credit = 0.0;
    data.forEach((element) {
      String balance = "${element.default_balance}";
      num nBalance = isEmpty(balance) ? 0 : num.parse(balance);
      if (element.crdr_nature == "DR") {
        debit = debit + nBalance;
      } else {
        credit = credit + nBalance;
      }
    });
    totalDebit = debit;
    totalCredit = credit;
    difference = "${totalDebit - totalCredit}";
  }

  void onSelectAsAt() {
    searchFocusNode.unfocus();
    obtainContext?.call((context) async {
      final result = await showDateTimeSelectBottomSheet(context, S.current.as_at, asAt);
      if (result != null) {
        searchController.clear();
        asAt = result;
        update();
        onRequestRefresh();
      }
    });
  }

  void onRequestRefresh() {
    post(dataFuture, loadingTip: S.current.loading, onSuccess: (result) {
      data = transformData(getEntityFromResult<List<SettingDataImportSummaryListEntity>>(result), false);
      update();
    });
  }

  void toNext() {
    if (isEmpty(difference) || num.parse(difference) != 0.0) return;

    obtainContext((context) {
      showLiInfoBottomSheet(context, S.current.confirm_import, fileItems, onDelete: () {
        Navigator.pop(context);
        _saveCoaDatas();
      }, sureBtnText: S.current.confirm, cancelText: S.current.cancel, li: true);
    });
  }

  _saveCoaDatas() async {
    obtainContext?.call((context) async {
      BaseConfig.dialogBase.showLoadingDialog(context: context, text: 'loading...');
      await post(HttpCoaService.saveCoaData(), autoHandler: AutoHandler.Toast, onSuccess: (result) {
        Navigator.pop(context);
        showSuccessTipBottomSheet(context, S.current.you_data_have_ben_imported_successfully);
      }).onError((error, stackTrace) {
        return showDeleteInfoBottomSheet(context, S.current.import_unsuccessful, error,
            onDelete: () {
              Navigator.pop(context);
              // uploadTemplateFile();
            },
            sureBtnText: S.current.redo_data_import,
            cancelText: S.current.return_to_settings,
            onCancel: () {
              Navigator.pop(context);
              Navigator.pop(context);
            });
      });
    });
  }
}
